package com.silverbox.sweeporder.service.index.impl;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.silverbox.shopper.entity.*;
import com.silverbox.sweeporder.common.PayMotionConstants;
import com.silverbox.sweeporder.controller.index.vo.*;
import com.silverbox.sweeporder.controller.shopcart.entryvo.UserBaseDto;
import com.silverbox.waimai.entity.TakeOutConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayMarketingCampaignDrawcampTriggerRequest;
import com.alipay.api.response.AlipayMarketingCampaignDrawcampTriggerResponse;
import com.silverbox.core.result.CoreResponse;
import com.silverbox.core.result.CoreResponse.StatusInfo;
import com.silverbox.core.util.CalendarUtil;
import com.silverbox.core.util.DateUtils;
import com.silverbox.core.util.HttpUtils;
import com.silverbox.core.util.StringUtils;
import com.silverbox.core.util.Utils;
import com.silverbox.shopper.dubboApi.goods.ShopperGoodsServiceApi;
import com.silverbox.shopper.dubboApi.info.ShopperInfoServiceApi;
import com.silverbox.shopper.dubboApi.order.OrderServiceApi;
import com.silverbox.shopper.entity.extend.CategoryGoods;
import com.silverbox.shopper.entity.extend.DecorationShopConfigDetailExtend;
import com.silverbox.shopper.entity.extend.EmployeeExtend;
import com.silverbox.shopper.entity.extend.GoodsExtendParam;
import com.silverbox.shopper.entity.extend.ShopperActivities;
import com.silverbox.shopper.entity.extend.ShopperAndParent;
import com.silverbox.shopper.entity.extend.ShopperInfo;
import com.silverbox.sweeporder.common.AlipayServiceEnvConstants;
import com.silverbox.sweeporder.common.CommConstant;
import com.silverbox.sweeporder.common.Constants;
import com.silverbox.sweeporder.common.util.AlipayUtils;
import com.silverbox.sweeporder.common.util.KeyGenerateRulesUtils;
import com.silverbox.sweeporder.common.util.MD5;
import com.silverbox.sweeporder.common.util.SweepOrderUtils;
import com.silverbox.sweeporder.controller.index.configvo.ComponentGroupVO;
import com.silverbox.sweeporder.controller.index.configvo.ComponentVO;
import com.silverbox.sweeporder.controller.index.configvo.DecorationVO;
import com.silverbox.sweeporder.controller.index.configvo.ModuleVO;
import com.silverbox.sweeporder.controller.index.configvo.PageVO;
import com.silverbox.sweeporder.controller.index.entryvo.SavePeopleNumVO;
import com.silverbox.sweeporder.controller.index.entryvo.ShowPeopleNumberVO;
import com.silverbox.sweeporder.controller.member.vo.EmployeeAuthRecordEntryVO;
import com.silverbox.sweeporder.controller.member.vo.FindEmployeeEntryVO;
import com.silverbox.sweeporder.service.employee.EmployeeService;
import com.silverbox.sweeporder.service.index.GoodsService;
import com.silverbox.sweeporder.service.index.IndexService;
import com.silverbox.sweeporder.service.redis.RedisService;
import com.silverbox.sweeporder.service.waimai.WaimaiOrderService;
import com.silverbox.waimai.dubboApi.goodscart.GoodsCartServiceApi;
import com.silverbox.waimai.dubboApi.order.WaimaiServiceApi;
import com.silverbox.waimai.dubboApi.shopper.BusinessInfoApi;
import com.silverbox.waimai.entity.GoodsCart;
import com.silverbox.waimai.entity.SweepClose;
import com.silverbox.waimai.entity.Waimai;
import com.silverbox.waimai.entity.extend.GoodsCartAndDetail;
import com.silverbox.waimai.entity.extend.WaimaiParam;

@Service
//@Transactional
public class IndexServiceImpl implements IndexService {
	private static Logger logger = LoggerFactory.getLogger(IndexServiceImpl.class);

	@Autowired
	private ShopperInfoServiceApi shopperInfoServiceApi;

	@Autowired
	private BusinessInfoApi businessInfoApi;

	@Autowired
	private GoodsCartServiceApi goodsCartServiceApi;

	@Autowired
	private WaimaiOrderService waimaiOrderService;

	@Autowired
	private WaimaiServiceApi waimaiServiceApi;

	@Autowired
	private GoodsService goodsService;
	
	@Autowired
	private ShopperGoodsServiceApi shopperGoodsServiceApi;
	
	@Autowired
	private OrderServiceApi orderServiceApi;
	
	@Autowired
	private RedisService<Serializable, Object> redisService;
	
	@Autowired
	private EmployeeService employeeService;
	
	@Value("${member.url}")
	private String memberUrl;

	@Value("${customCommonCode}")
	private String customCommonCode;

	@Value("${customSpecialCode}")
	private String customSpecialCode;

	@Value("${customPublicKey}")
	private String customPublicKey;

	@Value("${sweepOrder.APP_ID}")
	private String sweepOrderAppId;

	@Value("${payment.ALIPAY_PUBLIC_KEY}")
	private String ALIPAY_PUBLIC_KEY;

	@Value("${payment.PRIVATE_KEY}")
	private String PRIVATE_KEY;

	@Value("${server.url}")
	private String serverUrl;

	@Value("${CLEAR_TABLE_MINUTE}")
	private String clear_table_minute;

	@Value("${koubeiUploadUrl}")
	private String koubeiUploadUrl;

	@Value("${uploadOrderFlag}")
	private String uploadOrderFlag;

	@Value("${PEOPLE_SELECT_RESET_TIME}")
	private String peopleResetTime;
	
	@Value("${sweepOrderVueUrl}")
	private String sweepOrderVueUrl;
	
	@Override
	public ShopperVO getShopper(Integer storeId) {
		ShopperAndParent shopper = shopperInfoServiceApi.getShopperAndParent(storeId);
		ShopperVO shopperVO = null;
		if (shopper != null) {
			shopperVO = new ShopperVO();
			BeanUtils.copyProperties(shopper, shopperVO);
			shopperVO.setParentId(shopper.getParentId());
			if (shopper.getParentInfo() != null) {
				shopperVO.setParentNick(shopper.getParentInfo().getNick());
				shopperVO.setParentMinLogo(shopper.getParentInfo().getMinLogo());
			}
		}
		return shopperVO;
	}

	@Override
	public Map<String, Object> getConfigByShopperId(Integer storeId) {
		Map<String, Object> shopperConfig = shopperInfoServiceApi.getShopperAllConfig(storeId);
		if (shopperConfig == null) {
			return null;
		}
		return shopperConfig;
	}

	@Override
	public ShopperConfig getShopperConfig(Integer storeId, String propName) {
		return shopperInfoServiceApi.getShopperConfig(storeId, propName);
	}

	@Override
	public DiningArea getDiningAreaById(Integer tableInfoId) {
		return shopperInfoServiceApi.getDiningAreaById(tableInfoId);
	}

	@Override
	public DiningArea getDiningAreaByUid(String uid) {
		return shopperInfoServiceApi.getDiningAreaByUid(uid);
	}

	@Override
	public ShopperExtend getShopperExtendById(Integer storeId) {
		ShopperExtend shopExtend = shopperInfoServiceApi.getShopperExtend(storeId);
		if (shopExtend != null) {
			String busTime = shopExtend.getBusinessTime();
			// 时间格式转换
			if (!StringUtils.isEmpty(busTime)) {
				if (busTime.substring(0, 1).equals("0")) {
					if (busTime.substring(6, 7).equals("0")) {
						shopExtend.setBusinessTime(busTime.substring(1, 6) + busTime.substring(7));
					} else {
						shopExtend.setBusinessTime(busTime.substring(1));
					}
				}
			} else {
				shopExtend.setBusinessTime("9:30~22:00");
			}
		}
		return shopExtend;
	}

	@Override
	public ShopperNotice getShopperNoticeDetail(Integer storeId) {
		String nowDate = DateUtils.getNowTime();
		return shopperInfoServiceApi.getShopperNotice(storeId, nowDate);
	}

	@Override
	public ThirdUserInfo getThirdUserInfoBuyerId(String buyerId, Integer source) {
		ThirdUserInfo thirdUserInfo = shopperInfoServiceApi.getThirdUserInfo(buyerId, source);
		if (thirdUserInfo != null) {
			String nickName = thirdUserInfo.getNickName() == null ? "吃货" : thirdUserInfo.getNickName();
			thirdUserInfo.setNickName(nickName);
		}
		return thirdUserInfo;
	}

	@Override
	public Map<String, Object> getAlipayShopIdByStoreId(Integer storeId) {
		Map<String, Object> thirdMap = new HashMap<String, Object>();
		ThirdPartyAuthorization thirdParty = shopperInfoServiceApi.getThirdPartyAuthorization(storeId);
		if (thirdParty != null) {
			thirdParty.getShopId();
			thirdParty.getMerchantPid();
			thirdMap.put("shopId", thirdParty.getShopId());
			thirdMap.put("merchanPid", thirdParty.getMerchantPid());
		}
		return thirdMap;
	}

	@Override
	public MemberInfoVO getMemberUserInfo(String buyerId) {
		// 验证会员信息是否绑定
		Map<String, String> nameValuePair = new HashMap<String, String>();
		String sign = MD5.md5crypt(customCommonCode + buyerId + customPublicKey + customSpecialCode);
		nameValuePair.put("alipayUserId", buyerId);
		nameValuePair.put("sign", sign);
		String url = memberUrl + "/waiMaiInterface/isBinding.htm";
		long startDate = System.currentTimeMillis();
		CoreResponse<String> result = HttpUtils.doPostForm(url, nameValuePair, 4000, 4000);
		long endDate = System.currentTimeMillis();
		JSONObject jo = JSONObject.parseObject(result == null ? null : result.getData());
		//logger.info("验证会员信息是否绑定查询时间====================" + (endDate - startDate));
		logger.info("验证会员信息:" + JSONObject.toJSONString(jo));
		MemberInfoVO memberInfo = null;
		if (jo == null || !jo.getBooleanValue("isBinding")) {
			memberInfo = new MemberInfoVO();
			memberInfo.setBinding(false);
			memberInfo.setUid("");
			memberInfo.setMobile("8006663907");
		}

		if (jo != null && jo.getBooleanValue("success")) {
			if (jo.getBooleanValue("isBinding")) {
				memberInfo = new MemberInfoVO();
				memberInfo.setBinding(true);
				memberInfo.setAvatar(jo.getString("avatar"));
				memberInfo.setMobile(jo.getString("mobile"));
				memberInfo.setNick(jo.getString("nick"));
				memberInfo.setUid(jo.getString("uid"));
			}
		}
		return memberInfo;
	}

	@Override
	public List<ShopperActivities> getShopperActivityList(String shopId) {
		String nowDate = DateUtils.getNowTime();
		return shopperInfoServiceApi.getShopperActivities(shopId, nowDate);
	}

	@Override
	public CoreResponse<CallServiceInfoCVO> getShopperCallService(Integer storeId, Integer tableInfoId) {

		CoreResponse<CallServiceInfoCVO> res = new CoreResponse<CallServiceInfoCVO>();

		ShopperConfig serviceConfig = shopperInfoServiceApi.getShopperConfig(storeId, "CTR_CALL_SERVICE");

		Integer serviceShopper = (serviceConfig == null || serviceConfig.getPropValue() == null) ? 0
				: Integer.valueOf(String.valueOf(serviceConfig.getPropValue()));
		if (!new Integer(1).equals(serviceShopper)) {
			res.setStatusInfo(StatusInfo.FORBIDDEN);
			res.setMsg("请开通呼叫服务");
			return res;
		}
		List<ShopperService> shopperCallService = shopperInfoServiceApi.getShopperService(storeId);
		List<CallServiceInfoVO> callService = new ArrayList<CallServiceInfoVO>();
		// 获取呼叫服务信息
		if (!CollectionUtils.isEmpty(shopperCallService)) {
			for (ShopperService shopperService : shopperCallService) {
				CallServiceInfoVO callServiceInfo = new CallServiceInfoVO();
				callServiceInfo.setId(shopperService.getId());
				callServiceInfo.setServiceName(shopperService.getServiceName());
				BeanUtils.copyProperties(shopperService, callServiceInfo);
				callService.add(callServiceInfo);
			}
		}

		EmployeeInfoVO employeeInfo = null;
		EmployeeExtend employee = null;
		// 获取桌台绑定的员工号
		if (tableInfoId != null) {
			employee = shopperInfoServiceApi.getRelTableEmployee(tableInfoId);
		}
		if (employee != null) {
			employeeInfo = new EmployeeInfoVO();
			BeanUtils.copyProperties(employee, employeeInfo);
		}
		CallServiceInfoCVO callServiceInfo = new CallServiceInfoCVO();
		callServiceInfo.setCallServiceInfoList(callService);
		callServiceInfo.setEmployeeInfo(employeeInfo);
		res.setData(callServiceInfo);
		return res;
	}

	@Override
	public Long getHostMachineId(Integer storeId) {
		EpayShopConfig epay = shopperInfoServiceApi.getEpayShopConfig(storeId);
		Long hostMachineId = null;
		if (epay != null) {
			hostMachineId = epay.getMachineId();
		}
		return hostMachineId;
	}

	@Override
	public Integer findByPropName(Integer storeId, String propName) {
		ShopperConfig shopperConfig = shopperInfoServiceApi.getShopperConfig(storeId, propName);
		Integer propValue = null;
		if (shopperConfig != null) {
			propValue = shopperConfig.getPropValue() == null ? null
					: Integer.valueOf(shopperConfig.getPropValue().toString());
		}
		return propValue;
	}

	@Override
	public CoreResponse<Map<String, Object>> getBusinessIsOrders(Integer storeId) {

		CoreResponse<Map<String, Object>> res = new CoreResponse<Map<String, Object>>();
		Map<String, Object> ordersMap = new HashMap<String, Object>();

		// 查询承接端是否开启接单按钮
		SweepClose sweepClose = businessInfoApi.getSweepCloseByStoreId(storeId);

		if (sweepClose != null) {
			sweepClose.setTime(sweepClose.getTime() + 1);
			long between = 0l;
			long hour = 0l;
			long min = 0l;
			long s = 0l;
			long warnTime = 0l;
			if (sweepClose.getCloseTime() != null) {
				between = (new Date().getTime() - sweepClose.getCloseTime().getTime()) / 1000;// 除以1000是为了转换成秒
			}
			hour = between / 3600;
			between = between - hour * 3600;
			min = between / 60;
			between = between - min * 60;
			s = between;
			if (sweepClose.getWarnTime() != null) {
				warnTime = (new Date().getTime() - sweepClose.getWarnTime().getTime()) / 1000;// 除以1000是为了转换成秒
			}
			if ((hour > 0 || min >= 5) && (sweepClose.getWarnTime() == null || warnTime / 60 >= 5)) {
				String msg = "";
				msg = hour > 0 ? (msg + hour + "小时") : msg;
				msg = hour > 0 ? (msg + min + "分") : (min > 0 ? (msg + min + "分") : msg);
				msg = min > 0 ? (msg + s + "秒") : (s > 0 ? (msg + s + "秒") : msg);
				ordersMap.put("time", sweepClose.getTime());
				ordersMap.put("msg", msg);
				ordersMap.put("isSend", 1);
				sweepClose.setWarnTime(new Date());
			} else {
				ordersMap.put("isSend", 0);
			}
			// 修改承接单是否开启接单按钮
			businessInfoApi.updateSweepClose(sweepClose);
		}
		ordersMap.put("state", sweepClose == null ? 0 : 1);
		res.setData(ordersMap);
		return res;
	}

	@Override
	public CoreResponse<Map<String, Object>> getReceiveRedEvenlope(String buyerId) {
		CoreResponse<Map<String, Object>> res = new CoreResponse<Map<String, Object>>();
		Map<String, Object> RedEvenlopeMap = new HashMap<String, Object>();

		Integer status = new Integer(0);

		AlipayClient alipayClient = AlipayUtils.initAlipayClientByAppId(PRIVATE_KEY, ALIPAY_PUBLIC_KEY,
				sweepOrderAppId);
		JSONObject json = new JSONObject();
		json.fluentPut("user_id", buyerId).fluentPut("camp_id", 61406);
		// 请求支付宝接口调用获取红包接口
		AlipayMarketingCampaignDrawcampTriggerRequest aliPayRequest = new AlipayMarketingCampaignDrawcampTriggerRequest();
		aliPayRequest.setBizContent(json.toJSONString());
		try {
			AlipayMarketingCampaignDrawcampTriggerResponse alipayResponse = alipayClient.execute(aliPayRequest);
			if (null != alipayResponse && alipayResponse.isSuccess()) {
				logger.info("领取红包成功，支付宝返回结果：" + (null == alipayResponse ? "null" : alipayResponse.getMsg()));
				status = new Integer(1);
				Integer trigger_result = null == alipayResponse.getTriggerResult() ? 0
						: (alipayResponse.getTriggerResult() ? 1 : 0);
				if (new Integer(1).equals(trigger_result)) {
					String prize_name = alipayResponse.getPrizeName();
					String extend_field = alipayResponse.getExtendField();
					Map<String, Object> map = JSONObject.parseObject(extend_field);
					RedEvenlopeMap.put("prize_name", prize_name);
					RedEvenlopeMap.put("extend_field", extend_field);
					RedEvenlopeMap.put("prize_amount",
							null == map.get("prize_amount") ? "0" : map.get("prize_amount").toString());
					res.setMsg("领取成功");
				} else {
					res.setStatusInfo(StatusInfo.NORESOURCE);
					res.setMsg("领取失败,已领取过红包或领取失败");
					status = 2;
				}
				RedEvenlopeMap.put("status", status);
				RedEvenlopeMap.put("trigger_result", trigger_result);
				res.setData(RedEvenlopeMap);
				return res;
			} else {
				logger.info("领取红包失败，支付宝返回结果：" + (null == alipayResponse ? "null" : alipayResponse.getMsg()));
				RedEvenlopeMap.put("status", new Integer(-3));
				res.setData(RedEvenlopeMap);
				res.setMsg("领取红包失败,领取红包异常");
				res.setStatusInfo(StatusInfo.NORESOURCE);
				return res;
			}
		} catch (Exception e) {
			logger.info("领取红包失败，请求支付宝异常：" + e.toString());
			RedEvenlopeMap.put("status", new Integer(-3));
			res.setData(RedEvenlopeMap);
			res.setStatusInfo(StatusInfo.NORESOURCE);
			res.setMsg("领取红包失败,请求支付宝异常");
			return res;
		}
	}

	@Override
	public Integer findByShopperIdAndPropName(Integer shopperId, String propName) {
		ShopperConfig shopperConfig = shopperInfoServiceApi.getShopperConfig(shopperId, propName);
		Integer propValue = null;
		if (shopperConfig != null) {
			propValue = shopperConfig.getPropValue() == null ? null
					: Integer.valueOf(shopperConfig.getPropValue().toString());
		}
		return propValue;
	}

	@Override
	public Map<String, Object> getShopperRenovationDefaultConfig(int decorationType) {
		return shopperInfoServiceApi.getShopperRenovationDefaultConfig(decorationType);
	}

	@Override
	public List<Long> getShopperRenovationByStoreId(Integer storeId,int decorationType) {
		return shopperInfoServiceApi.getShopperRenovationByStoreId(storeId,decorationType);
	}

	@Override
	public JSONObject getShopperRenovationByShopperId(Long configId,int decorationType) {
		// 获取绑定的店铺已发布的模板配置
		String reslut = shopperInfoServiceApi.getShopperRenovationByShopperId(configId,decorationType);
		if (StringUtils.isNotEmpty(reslut)) {
			JSONObject json = JSONObject.parseObject(reslut);
			return json;
		}
		return null;
	}

	@Override
	public ShopperInfoVO getShopperInfo(Integer storeId, String nowDate) {
		ShopperInfo shopper = shopperInfoServiceApi.getShopperInfo(storeId, nowDate);
		//logger.info("shopper:"+shopper.toString());
		ShopperInfoVO shopperInfoVO = null;
		if (shopper != null) {
			shopperInfoVO = new ShopperInfoVO();
			BeanUtils.copyProperties(shopper, shopperInfoVO);
			shopperInfoVO.setAliPayUserId(shopper.getStoreAliPayId());
			// 店铺营业时间处理
			if (shopper.getStoreBusTime() != null) {
				String busTime = shopper.getStoreBusTime();
				// 时间格式转换
				if (!StringUtils.isEmpty(busTime)) {
					if (busTime.substring(0, 1).equals("0")) {
						if (busTime.substring(6, 7).equals("0")) {
							shopperInfoVO.setStoreBusTime(busTime.substring(1, 6) + busTime.substring(7));
						} else {
							shopperInfoVO.setStoreBusTime(busTime.substring(1));
						}
					}
				} else {
					shopperInfoVO.setStoreBusTime("9:30~22:00");
				}
			}
		}
		return shopperInfoVO;
	}

	@Override
	public CoreResponse<ShopperInfoVO> getShopperInfoService(Integer storeId, Integer tableInfoId, String buyerId,
			Integer clientOrderMode) {
		CoreResponse<ShopperInfoVO> res = new CoreResponse<ShopperInfoVO>();
		// 查询店铺信息
		ShopperInfoVO shopperInfo = getShopperInfo(storeId, DateUtils.getNowTime());
		//logger.info("shopperInfo:"+shopperInfo.toString());
		if (shopperInfo == null || shopperInfo.getShopperId() == null) {
			res.setStatusInfo(StatusInfo.FORBIDDEN);
			res.setMsg("主店铺信息获取异常");
			return res;
		}
		// 查询店铺配置
		Map<String, Object> shopperConfig = null;
		ShopperConfigVO shopperConfigVO = new ShopperConfigVO();
		ShopperConfigExtend shopperConfigExt;
		// 获取redis店铺配置信息
		Object config = redisService.getObj(storeId + "_shopperConfig");
		logger.info("获取redis店铺配置信息config:"+JSONObject.toJSONString(redisService.getObj(storeId + "_shopperConfig")));
        if (config == null) {
			// 查询店铺所有配置
			shopperConfig = shopperInfoServiceApi.getShopperAllConfig(storeId);
			if (shopperConfig == null) {
				res.setStatusInfo(StatusInfo.FORBIDDEN);
				res.setMsg("店铺配置异常");
				return res;
			}
			// map转成对象
			shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopperConfig);
		} else {
			shopperConfigExt = (ShopperConfigExtend) config;
		}
        Shopper shopper = shopperInfoServiceApi.getShopper(storeId);
        //是否开通会员积分抵扣是根据主账号控制
        ShopperConfig isOpendMemberScore = shopperInfoServiceApi.getShopperConfig(shopper.getParentId(), "IS_OPEND_MEMBER_SCORE_DECUCTION");
        if (shopperConfigExt != null) {
            shopperConfigExt.setIsOpendMemberScoreDecuction(Utils.isEmpty(isOpendMemberScore) || Utils.isEmpty(isOpendMemberScore.getPropValue()) ? 0 :1);
        }
        Long hostMachineId = null;
		// map转成对象
		/*shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopperConfig);
		redisService.setObj(storeId + "_shopperConfig", shopperConfigExt,24L,TimeUnit.HOURS);*/
		BeanUtils.copyProperties(shopperConfigExt, shopperConfigVO);
		// 是否支持数据回流
		if (new Integer(1).equals(shopperConfigExt.getOnlineDataBackflow())) {
			// 获取数据回流主机Id
			EpayShopConfig epayShopConfig = shopperInfoServiceApi.getEpayShopConfig(storeId);
			if (epayShopConfig != null) {
				hostMachineId = epayShopConfig.getMachineId();
			}
		}
		if(new Integer(1).equals(shopperConfigExt.getIntelligenceCabinet())){
			RelMachineHardWare machineHard = new RelMachineHardWare();
			machineHard.setStoreId(storeId);
			machineHard.setType(2);
			machineHard.setThirdMachineBrand("pinyuan");
			//查询如果有品元的机器，则要判断取餐码唯一性
			RelMachineHardWare hardWare = orderServiceApi.getMachineHardWareInfo(machineHard);
			if(hardWare!=null){
				shopperConfigVO.setOnlineCupboardType(1);
			}else{
				shopperConfigVO.setOnlineCupboardType(0);
			}
		}
		shopperConfigVO.setHostMachineId(hostMachineId);
		
		ShopperWhiteListVO shopperWhite = getShopperWhite(storeId, shopperInfo.getShopperId());
		// 判断是否有未完成订单，
		Integer modeType = 0;
		// 查询店铺桌台信息
		DiningArea tableInfo = null;
		if (tableInfoId != null) {
			tableInfo = shopperInfoServiceApi.getDiningAreaById(tableInfoId);
			if (tableInfo != null) {
				String startDate = DateUtils.getYesterdayStartTime();
				String endDate = DateUtils.getTodayEndTime();
				// 查询未完成订单
                logger.info("index加载门店信息,clientOrderMode="+clientOrderMode);
                Integer md = Constants.orderOutSupportId.WAIMAI_ORDER.getValue().equals(Long.valueOf(clientOrderMode)) ? 4 : null;
				Waimai waimai = waimaiOrderService.hasUnfinishedOrder(storeId, tableInfo.getName(),md);
				// 清空购物车判断
				int deleteCount = deleteGoodsCart(shopperConfigExt.getClearCartTime(),
						shopperConfigExt.getFirstPayMent(),shopperWhite.getClearTable(), storeId, buyerId, tableInfo,
						waimai);
				if (waimai != null && deleteCount == 0) {
					shopperConfigVO.setPeopleNumber(waimai.getPeopleNumber());
					modeType = 1;
				} else {
					Integer peopleNumber = redisService.getObj(storeId + "_" + tableInfo.getId()+"_peopleNumber") == null ? 0
							: Integer.valueOf(String.valueOf(redisService.getObj(storeId + "_" + tableInfo.getId()+"_peopleNumber")));
					shopperConfigVO.setPeopleNumber(peopleNumber);
					//logger.info("获取就餐人redis===========" + peopleNumber);
				}
				// 更新购物车（入座）需要在清空购物车操作之后，否则会出现排队时扫门店码加入购物车，等较长时间后再扫桌码，会将之前的购物车清空的问题
				// 之所以改为先查询后更新,因为出现过根据非主键索引更新出现死锁情况
				List<GoodsCartAndDetail> cartList = goodsCartServiceApi.getGoodsCartByBuyerId(storeId, buyerId,
						startDate, endDate,clientOrderMode);
				int cartCount = 0;
				if (!CollectionUtils.isEmpty(cartList)) {
					List<Integer> cartId = new ArrayList<Integer>();
					for (GoodsCartAndDetail cart : cartList) {
						if (StringUtils.isEmpty(cart.getTableNo())) {
							cartId.add(cart.getId());
						}
					}
					// 将该用户在前台购物车中的购物车明细增加tableNo
					if (!CollectionUtils.isEmpty(cartId)) {
						cartCount = goodsCartServiceApi.updateGoodsCartForTableNo(cartId, tableInfo.getName());
					}
				}
				if (cartCount > 0) {
					modeType = 2;
				}
			}
		} 
		// 获取是否显示用餐人数页
		// 查询店铺是否开启扫码下单店铺装修配置
		Integer renovationShopper = findByPropName(shopperInfo.getShopperId(), "IS_OPEN_SWEEPORDER_DECORATION");
		if (new Integer(1).equals(renovationShopper)
				&& (shopperConfigVO.getPeopleNumber() == null || shopperConfigVO.getPeopleNumber() == 0)) {
			int decorationType = 0;
			//在线订单类型
            if((Constants.clientOrderMode.ONLINE_ORDER_MODE.getValue()).equals(clientOrderMode)
                    || (Constants.clientOrderMode.WAIMAI_ORDER_MODE.getValue()).equals(clientOrderMode)){
				decorationType=1;
			}
			// 查询是否绑定了店铺装修风格
			List<Long> list = shopperInfoServiceApi.getShopperRenovationByStoreId(storeId,decorationType);
			// 获取店铺装修配置 显示用餐人数页条件
			String pageCode = "P_Meal_Numbers";
			String componentCode = "A_Numbers_Show";
			String componentPage = "A_Numbers_Page";
			Integer renovationCount = 0;
			Integer renovationPage = 0;
			if (!CollectionUtils.isEmpty(list)) {
				// 绑定了则查询商家自定义的店铺装修风格的用餐人数页配置
				renovationCount = shopperInfoServiceApi.getShopperRenovationCustomPage(storeId, pageCode,
						componentCode,decorationType);
				renovationPage = shopperInfoServiceApi.getShopperRenovationCustomPage(storeId, pageCode, componentPage,decorationType);
			} else {
				// 获取店铺装修默认是否显示用餐人数页
				renovationCount = shopperInfoServiceApi.getShopperRenovationPage(pageCode, componentCode,decorationType);
				renovationPage = shopperInfoServiceApi.getShopperRenovationPage(pageCode, componentPage,decorationType);
			}
			if (renovationCount >= 1 && renovationPage >= 1) {
				// 如果店铺装修开启人数选择且为页面时
				modeType = 3;
			}
		}
		// add by hyc 2019年12月19日15:20:29
		//获取店铺公告
		String nowDate = DateUtils.getNowTime();
		List<ShopperNotice> listStoreNotice = shopperInfoServiceApi.getNoticeDetail(storeId,nowDate);
		List<ShopperNoticeVO> listStoreNoticeVO = new ArrayList<ShopperNoticeVO>();
		for (ShopperNotice shopperNotice : listStoreNotice) {
			ShopperNoticeVO  shopperNoticeVO = new ShopperNoticeVO();
			BeanUtils.copyProperties(shopperNotice, shopperNoticeVO);
			listStoreNoticeVO.add(shopperNoticeVO);
		}
		shopperConfigVO.setModeType(modeType);
		shopperConfigVO.setServerUrl(serverUrl);
		//查询该店铺下是否开通了图形模式
		boolean flag = shopperInfoServiceApi.getMachineConfig(storeId);
		if(flag){
			shopperConfigVO.setIsOpenDinnerGui(1);
		}else{
			shopperConfigVO.setIsOpenDinnerGui(0);
		}
		DiningAreaVO diningAreaVO = null;
		if (tableInfo != null) {
			diningAreaVO = new DiningAreaVO();
			BeanUtils.copyProperties(tableInfo, diningAreaVO);
			diningAreaVO.setTableName(tableInfo.getName());
		}

		//外卖配置
        TakeOutConfigVo takeOutConfigVo = new TakeOutConfigVo();
        TakeOutConfig takeOutConfig = shopperInfoServiceApi.getTakeOutConfigByStoreId(storeId);
		if(takeOutConfig != null){
            takeOutConfigVo.setMaxTakeOutDistance(takeOutConfig.getMaxTakeOutDistance());
            takeOutConfigVo.setMinimumDeliveryAmount(takeOutConfig.getMinimumDeliveryAmount());
            takeOutConfigVo.setTakeOutBook(takeOutConfig.getTakeOutBook());
            takeOutConfigVo.setTakeOutMethod(takeOutConfig.getTakeOutMethod());
            takeOutConfigVo.setTakeOutOpen(takeOutConfig.getTakeOutOpen());
            takeOutConfigVo.setTakeOutPeriodType(takeOutConfig.getTakeOutPeriodType());
            takeOutConfigVo.setTakeOutThirdShopOpen(takeOutConfig.getTakeOutThirdShopOpen());
        }

		//20200427门店活动信息
//        List<PromotionInfoVO> promotionInfoList =  shopperInfoServiceApi.findStorePromotionInfoList(storeId);
        shopperInfo.setTakeOutConfig(takeOutConfigVo);
        shopperInfo.setDiningArea(diningAreaVO);
		shopperInfo.setShopperConfig(shopperConfigVO);
		shopperInfo.setShopperWhite(shopperWhite);
		shopperInfo.setListStoreNotice(listStoreNoticeVO);
//        shopperInfo.setPromotionInfoList(promotionInfoList);
		res.setData(shopperInfo);
		return res;
	}

	@Override
	public ShopperConfigExtend getShopperConfig(Integer storeId) {
		Map<String, Object> shopperConfig = shopperInfoServiceApi.getShopperAllConfig(storeId);
		if (shopperConfig == null) {
			return null;
		}
		ShopperConfigExtend shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopperConfig);
		return shopperConfigExt;
	}


	/**
	 * 获取店铺白名单配置
	 * 
	 * @param storeId
	 * @param shopperId
	 * @return
	 */
	public ShopperWhiteListVO getShopperWhite(Integer storeId, Integer shopperId) {
		// 查询所有白名单
		ShopperWhiteListVO shopperWhite = new ShopperWhiteListVO();
		Map<String,Integer> map = new HashMap<String,Integer>();
		//过滤了停用的白名单
		List<BusinessEncoding> businessEncodList = shopperInfoServiceApi.getAllBusinessEncoding();
		if (!CollectionUtils.isEmpty(businessEncodList)) {
			for (BusinessEncoding business : businessEncodList) {
				// 购物车金额不显示
				if ((CommConstant.WHILET_NOT_TOTAL_PRICE).equals(business.getCode())) {
					if (new Integer(2).equals(business.getStatus())) {
						shopperWhite.setBlackTotalPrice(0);
					} else {
						shopperWhite.setBlackTotalPrice(1);
					}
					continue;
				}
				// 不显示打包按钮
				if ((CommConstant.WHILET_NOT_SHOW_PACK).equals(business.getCode())) {
					if (new Integer(2).equals(business.getStatus())) {
						shopperWhite.setBlackBagButton(0);
					} else {
						shopperWhite.setBlackBagButton(1);
					}
					continue;
				}
				// 同桌重复菜品提示
				if ((CommConstant.WHILET_REPEAT_GOODS_REMIND).equals(business.getCode())) {
					if (new Integer(2).equals(business.getStatus())) {
						shopperWhite.setRepeatGoodsRemind(1);
					} else {
						shopperWhite.setRepeatGoodsRemind(0);
					}
					continue;
				}
				// 口碑推荐菜
				if ((CommConstant.WHILET_SHOW_KOUBEI_RECOMMEND).equals(business.getCode())) {
					if (new Integer(2).equals(business.getStatus())) {
						shopperWhite.setShowKoubeiRecommend(1);
					} else {
						shopperWhite.setShowKoubeiRecommend(0);
					}
					continue;
				}
				// 清台
				if ((CommConstant.WHILET_CLEAR_TABLE).equals(business.getCode())) {
					if (new Integer(2).equals(business.getStatus())) {
						shopperWhite.setClearTable(1);
					} else {
						shopperWhite.setClearTable(0);
					}
					continue;
				}
				//商品分类关联
				if((CommConstant.WHILET_SWEEP_STORE_CATEGORY).equals(business.getCode())){
					if(new Integer(2).equals(business.getStatus())){
						map.put("storeCategory", 1);
					}else{
						map.put("storeCategory", 0);
					}
					continue;
				}
				//加料商品加入购物车判断
				if((CommConstant.WHILET_CHECK_GOODS_PROP).equals(business.getCode())){
					if(new Integer(2).equals(business.getStatus())){
						map.put("checkGoodsProp", 1);
					}else{
						map.put("checkGoodsProp", 0);
					}
					continue;
				}
				//点击开始点餐跳转到支付宝生活号
				if((CommConstant.WHILET_SWEEP_JUMP_ALIPAY_LIFE).equals(business.getCode())){
					if(new Integer(2).equals(business.getStatus())){
						shopperWhite.setJumpALipayLife(1);
					}else{
						shopperWhite.setJumpALipayLife(0);
					}
					continue;
				}
				//扫码点餐是否需要绑定手机号
				if((CommConstant.WHILET_SWEEP_BIND_CELL_PHONE).equals(business.getCode())){
					if(new Integer(2).equals(business.getStatus())){
						shopperWhite.setBindCellPhone(1);
					}else{
						shopperWhite.setBindCellPhone(0);
					}
				}
				// 在线订单判断是否二次扫码进入历史订单页面白名单
				if((CommConstant.WHILET_SWEEP_REPEAT_JUMP_PAGE).equals(business.getCode())){
					if(new Integer(2).equals(business.getStatus())){
						shopperWhite.setRepeatJumpPage(1);
					}else{
						shopperWhite.setRepeatJumpPage(0);
					}
				}
				// 在线订单支付完成后不跳转支付完成页面白名单
				if((CommConstant.WHILET_NOT_SWEEP_JUMP_PAY_PAGE).equals(business.getCode())){
					if(new Integer(2).equals(business.getStatus())){
						shopperWhite.setNotJumpPayPage(0);
					}else{
						shopperWhite.setNotJumpPayPage(1);
					}
				}
                // 是否自动核销
                if((CommConstant.SWEEP_ORDER_AUTO_WRITE_OFF_PROHIBIT).equals(business.getCode())){
                    if(new Integer(2).equals(business.getStatus())){
                        shopperWhite.setNotAutoWriteOff(1);
                    }else{
                        shopperWhite.setNotAutoWriteOff(0);
                    }
                }
			}
		}
		// 查询店铺配置白名单
		List<BusinessWhiteList> BusinessWhiteList = shopperInfoServiceApi.getShopperBusinessWhiteList(storeId,
				shopperId,null);
		if (!CollectionUtils.isEmpty(BusinessWhiteList)) {
			for (BusinessWhiteList white : BusinessWhiteList) {
                //自动核销
                if ((CommConstant.SWEEP_ORDER_AUTO_WRITE_OFF_PROHIBIT).equals(white.getCode())) {
                    shopperWhite.setNotAutoWriteOff(1);
                }
				// 购物车金额不显示
				if ((CommConstant.WHILET_NOT_TOTAL_PRICE).equals(white.getCode()) && shopperWhite.getBlackTotalPrice()!=null) {
					shopperWhite.setBlackTotalPrice(0);
					continue;
				}
				// 不显示打包按钮
				if ((CommConstant.WHILET_NOT_SHOW_PACK).equals(white.getCode()) && shopperWhite.getBlackBagButton()!=null) {
					shopperWhite.setBlackBagButton(0);
					continue;
				}

				// 同桌重复菜品提示
				if ((CommConstant.WHILET_REPEAT_GOODS_REMIND).equals(white.getCode()) && shopperWhite.getRepeatGoodsRemind()!=null) {
					shopperWhite.setRepeatGoodsRemind(1);
					continue;
				}
				// 口碑推荐菜
				if ((CommConstant.WHILET_SHOW_KOUBEI_RECOMMEND).equals(white.getCode())&& shopperWhite.getShowKoubeiRecommend()!=null) {
					shopperWhite.setShowKoubeiRecommend(1);
					continue;
				}
				// 清台
				if ((CommConstant.WHILET_CLEAR_TABLE).equals(white.getCode()) && shopperWhite.getClearTable()!=null) {
					shopperWhite.setClearTable(1);
					continue;
				}
				//商品分类关联
				if((CommConstant.WHILET_SWEEP_STORE_CATEGORY).equals(white.getCode()) && map.get("storeCategory")!=null){
					map.put("storeCategory", 1);
					continue;
				}
				//加料商品加入购物车判断
				if((CommConstant.WHILET_CHECK_GOODS_PROP).equals(white.getCode()) && map.get("checkGoodsProp")!=null){
					map.put("checkGoodsProp", 1);
					continue;
				}
				//判断是否需要绑定手机号
				if((CommConstant.WHILET_SWEEP_BIND_CELL_PHONE).equals(white.getCode()) && shopperWhite.getBindCellPhone()!=null){
					shopperWhite.setBindCellPhone(1);;
					continue;
				}
				if((CommConstant.WHILET_SWEEP_JUMP_ALIPAY_LIFE).equals(white.getCode()) && shopperWhite.getJumpALipayLife()!=null){
					shopperWhite.setJumpALipayLife(1);
				}
				// 在线订单判断是否二次扫码进入历史订单页面白名单
				if((CommConstant.WHILET_SWEEP_REPEAT_JUMP_PAGE).equals(white.getCode()) && shopperWhite.getJumpALipayLife()!=null){
					shopperWhite.setRepeatJumpPage(1);
				}
				// 在线订单支付完成后不跳转支付完成页面白名单
				if((CommConstant.WHILET_NOT_SWEEP_JUMP_PAY_PAGE).equals(white.getCode()) && shopperWhite.getJumpALipayLife()!=null){
					shopperWhite.setNotJumpPayPage(0);
				}
			}
		}
        // 默认自动核销
        if (shopperWhite.getNotAutoWriteOff() == null) {
            shopperWhite.setNotAutoWriteOff(0);
        }
		// 默认显示打包按钮
		if (shopperWhite.getBlackBagButton() == null) {
			shopperWhite.setBlackBagButton(1);
		}
		// 默认显示总金额
		if (shopperWhite.getBlackTotalPrice() == null) {
			shopperWhite.setBlackTotalPrice(1);
		}
		// 默认不清台
		if (shopperWhite.getClearTable() == null) {
			shopperWhite.setClearTable(0);
		}
		// 同桌重复菜提示默认不提示
		if (shopperWhite.getRepeatGoodsRemind() == null) {
			shopperWhite.setRepeatGoodsRemind(0);
		}
		// 口碑推荐菜默认不显示
		if (shopperWhite.getShowKoubeiRecommend() == null) {
			shopperWhite.setShowKoubeiRecommend(0);
		}
		if(shopperWhite.getJumpALipayLife()==null){
			shopperWhite.setJumpALipayLife(0);
		}
		//是否需要绑定手机号
		if(shopperWhite.getBindCellPhone()==null){
			shopperWhite.setBindCellPhone(0);
		}
		// 在线订单判断是否二次扫码进入历史订单页面白名单
		if(shopperWhite.getRepeatJumpPage()==null){
			shopperWhite.setRepeatJumpPage(0);
		}
		// 在线订单支付完成后不跳转支付完成页面白名单
		if(shopperWhite.getNotJumpPayPage()==null){
			shopperWhite.setNotJumpPayPage(1);
		}
		// 商品分类关联默认
		if (map.get("storeCategory") == null) {
			map.put("storeCategory", 0);
		}
		// 商品分类关联默认
		if (map.get("checkGoodsProp") == null) {
			map.put("checkGoodsProp", 0);
		}
		// logger.info("存放redis的白名单信息"+JSON.toJSONString(map));
		redisService.setObj(storeId+"_shopperWhite", map,24L,TimeUnit.HOURS);
		return shopperWhite;
	}

	/**
	 * 清空购物车数据
	 */
	public int deleteGoodsCart(Integer clearCartTime, Integer firstPay, Integer clearTable, Integer storeId,
			String buyerId, DiningArea tableInfo, Waimai waimai) {
		int deleteCount = 0;
		if ((clearCartTime > 0 && !StringUtils.isEmpty(tableInfo.getName())) || (new Integer(1).equals(firstPay)
				&& new Integer(1).equals(clearTable) && !StringUtils.isEmpty(tableInfo.getName()))) {
			// 商家后台设置清空购物车时间
			clearCartTime = (clearCartTime==null ||clearCartTime==0)?Integer.valueOf(clear_table_minute):clearCartTime;
			goodsCartServiceApi.deleteGoodsCartByTableName(storeId, tableInfo.getName(),
					DateUtils.transTimeForString(clearCartTime));
			// 清除N分钟之前未付款的订单（-1，所有的）
			if (waimai != null && new Integer(0).equals(waimai.getPayStatus())) {
				WaimaiParam waimaiParams = new WaimaiParam();
				
				waimaiParams.setStoreId(storeId);
				waimaiParams.setShopperId(waimai.getShopperId());
				waimaiParams.setStatus(-1);
				waimaiParams.setTableUid(tableInfo.getUid());
				waimaiParams.setStartDate(DateUtils.getYesterdayStartTime());
				waimaiParams.setEndDate(DateUtils.transTimeForString(clearCartTime));
				deleteCount = waimaiServiceApi.updateWaimaiByCleanTable(waimaiParams);
				if (!StringUtils.isEmpty(waimai.getKoubeiShopid())) {
					waimaiServiceApi.uploadOrder(waimai, waimai.getOrderNum(), koubeiUploadUrl,
							uploadOrderFlag,waimai.getOuterSupportId());
				}
			}
		} else  {
			// 判断是否先付后吃
			if (new Integer(1).equals(firstPay)){
				// 清除三分钟前未付款的订单（-1，并且不是自己的）
				WaimaiParam waimaiParams = new WaimaiParam();
				waimaiParams.setStoreId(storeId);
				waimaiParams.setStatus(-1);
				waimaiParams.setTableUid(tableInfo.getUid());
				waimaiParams.setBuyerId(buyerId);
				Integer cleanMinute = Integer.valueOf(clear_table_minute);
				waimaiParams.setStartDate(DateUtils.getYesterdayStartTime());
				waimaiParams.setEndDate(DateUtils.transTimeForString(cleanMinute));
				deleteCount = waimaiServiceApi.updateWaimaiByCleanTable(waimaiParams);
			}
		}
		return deleteCount;
	}

	@Override
	public CoreResponse<Map<String, Object>> saveEatPeopleNum(SavePeopleNumVO savePeopleNum) {

		CoreResponse<Map<String, Object>> res = new CoreResponse<Map<String, Object>>();

		ShopperConfig shopperConfig = shopperInfoServiceApi.getShopperConfig(savePeopleNum.getStoreId(),
				"PEOPLE_SELECT_RESET_TIME");
		//获取默认保存人数时间
		long resetTime = Long.valueOf(peopleResetTime);
		//如果店铺配置进行了设置则以店铺配置优先
		if (shopperConfig != null && Long.valueOf(shopperConfig.getPropValue()) > 0) {
			resetTime = Long.valueOf(shopperConfig.getPropValue());
		}
		
		// 获取redis店铺配置信息
		Object config = redisService.getObj(savePeopleNum.getStoreId() + "_shopperConfig");
		ShopperConfigExtend shopperConfigExt = null;
		if (config == null) {
			// 查询店铺所有配置
			Map<String, Object> shopConfig = shopperInfoServiceApi.getShopperAllConfig(savePeopleNum.getStoreId());
			// map转成对象
			shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopConfig);
		} else {
			shopperConfigExt = (ShopperConfigExtend) config;
		}
		
		// redis保存就餐人数
		if (savePeopleNum.getTableInfoId() != null) {
			if (shopperConfigExt != null && new Integer(1).equals(shopperConfigExt.getFirstPayMent()) && new Integer(1).equals(shopperConfigExt.getIsOpenDeskmateSinglePoint())) {
				redisService.setObj(savePeopleNum.getStoreId() + "_" + savePeopleNum.getTableInfoId() + "_" + savePeopleNum.getBuyerId() + "_peopleNumber"
					, savePeopleNum.getPeopleNumber(), resetTime, TimeUnit.MINUTES);
			} else {
				redisService.setObj(savePeopleNum.getStoreId() + "_" + savePeopleNum.getTableInfoId()+"_peopleNumber"
					, savePeopleNum.getPeopleNumber(), resetTime, TimeUnit.MINUTES);
			}
		} else {
			redisService.setObj(savePeopleNum.getStoreId() + "_" + savePeopleNum.getBuyerId()+"_peopleNumber"
				, savePeopleNum.getPeopleNumber(), resetTime, TimeUnit.MINUTES);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("peopleNumber", savePeopleNum.getPeopleNumber());
		if (savePeopleNum.getTableInfoId() != null && new Integer(1).equals(shopperConfigExt.getFirstPayMent()) && new Integer(1).equals(shopperConfigExt.getIsOpenDeskmateSinglePoint())) {
			map.put("mustGoods", 0);
		} else {
			//人数改变时修改绑定人数必选菜数量
			GoodsExtendParam goodsExtendParam = new GoodsExtendParam();
			goodsExtendParam.setStoreId(savePeopleNum.getStoreId());
			goodsExtendParam.setShopperId(savePeopleNum.getShopperId());
			DiningArea diningArea = null;
			if(savePeopleNum.getTableInfoId()!=null){
				diningArea = shopperInfoServiceApi.getDiningAreaById(savePeopleNum.getTableInfoId());			
			}
			if(diningArea!=null){
				goodsExtendParam.setTableUid(diningArea.getUid());
			}
			String startDate = DateUtils.getYesterdayStartTime();
			String endDate = DateUtils.getTodayEndTime();
			String nowDate = DateUtils.getNowTime();
			goodsExtendParam.setStartDate(startDate);
			goodsExtendParam.setEndDate(endDate);
			goodsExtendParam.setNowDate(nowDate);
			goodsExtendParam.setIsRelatedPerson(1);
			//只查询关联人数的必选菜
			List<CategoryGoods> personNeedGoods = shopperGoodsServiceApi.getNeedGoodsInfoList(goodsExtendParam);
			List<GoodsCartAndDetail> goodsCart = new ArrayList<GoodsCartAndDetail>();
			
			if (diningArea!=null && StringUtils.isNotEmpty(diningArea.getName())) {
				goodsCart = goodsCartServiceApi.getGoodsCartByTableNo(savePeopleNum.getStoreId(), diningArea.getName(), startDate, endDate,savePeopleNum.getClientOrderMode());
			}else{
				goodsCart = goodsCartServiceApi.getGoodsCartByBuyerId(savePeopleNum.getStoreId(), savePeopleNum.getBuyerId(),startDate, endDate,savePeopleNum.getClientOrderMode());
			}
			
			int i=0;
			for (CategoryGoods categoryGoods : personNeedGoods) {
				for (GoodsCartAndDetail goodsCartAndDetail : goodsCart) {
					if((categoryGoods.getGoodsId().equals(goodsCartAndDetail.getGoodsId())) && (categoryGoods.getSizeId().equals(goodsCartAndDetail.getSizeId()))){
						GoodsCart newGoodsCart = new GoodsCart();
						newGoodsCart.setBuyCount(Double.valueOf(categoryGoods.getDefaultAdd() * savePeopleNum.getPeopleNumber()));
						newGoodsCart.setId(goodsCartAndDetail.getId());
						goodsCartServiceApi.updateGoodsCart(newGoodsCart);
						i++;
					}
				}
			}
			Integer mustGoods = 0;
			if(i>0){
				mustGoods = 1;
			}
//			NeedGoodsAddCart needGoods = new NeedGoodsAddCart();
	//
//			needGoods.setBuyerId(savePeopleNum.getBuyerId());
//			needGoods.setPeopleNumber(savePeopleNum.getPeopleNumber());
//			needGoods.setShopperId(savePeopleNum.getShopperId());
//			needGoods.setStoreId(savePeopleNum.getStoreId());
//			needGoods.setTableInfoId(savePeopleNum.getTableInfoId());
//			// 判断登录模式
//			if (!new Integer(2).equals(savePeopleNum.getAuthMode())) {
//				savePeopleNum.setAuthMode(1);
//			}
//			needGoods.setAuthMode(savePeopleNum.getAuthMode());
//			
//			
//			
//			
//			// 人数改变时调必点菜接口
//			CoreResponse<Map<String, Integer>> needRes = goodsService.getNeedGoodsAddCart(needGoods);
//			Integer mustGoods = 0;
//			if (needRes != null && needRes.getData() != null) {
//				mustGoods = needRes.getData().get("mustGoods");
//			}
			map.put("mustGoods", mustGoods);
		}
		res.setSubMsg("保存就餐人数成功");
		res.setData(map);
		return res;
	}

	@Override
	public CoreResponse<DecorationVO> getShopperDecorationInfo(Integer storeId, Integer shopperId,int decorationType) {
		CoreResponse<DecorationVO> res = new CoreResponse<DecorationVO>();
		// 查询店铺是否开启扫码下单店铺装修配置
		ShopperConfig shopperConfig = shopperInfoServiceApi.getShopperConfig(shopperId,
				"IS_OPEN_SWEEPORDER_DECORATION");
		List<DecorationShopConfigDetailExtend> pageDetail = null;
		// 如果开启店铺装修
		if (shopperConfig != null && new Integer(1).equals(shopperConfig.getPropValue())) {
			List<Long> list = shopperInfoServiceApi.getShopperRenovationByStoreId(storeId,decorationType);
			// 查询商家自定义的装修配置
			if (!CollectionUtils.isEmpty(list)) {
				pageDetail = shopperInfoServiceApi.getShopperPageDetail(storeId,decorationType);
			}
			// 商品未配置自定义配置 查询默认装修配置信息
			if (CollectionUtils.isEmpty(list) || CollectionUtils.isEmpty(pageDetail)) {
				pageDetail = shopperInfoServiceApi.getShopperDefaultPageDetail(decorationType);
			}
		} else {
			pageDetail = shopperInfoServiceApi.getShopperDefaultPageDetail(decorationType);
		}

		if (CollectionUtils.isEmpty(pageDetail)) {
			res.setStatusInfo(StatusInfo.NORESOURCE);
			res.setSubMsg("获取店铺装修配置失败");
			return res;
		}

		DecorationVO decoration = new DecorationVO();

		Map<Long, DecorationVO> styleMap = new HashMap<Long, DecorationVO>();
		Map<Long, PageVO> pageMap = new HashMap<Long, PageVO>();
		Map<String, ModuleVO> moduleMap = new HashMap<String, ModuleVO>();

		Map<String, List<ComponentVO>> tempComponent = new HashMap<String, List<ComponentVO>>();
		Map<String, List<ComponentGroupVO>> tempComponentGroup = new HashMap<String, List<ComponentGroupVO>>();

		for (DecorationShopConfigDetailExtend detail : pageDetail) {
			// 组装风格配置
			decoration = styleMap.get(detail.getStyleId());
			if (detail.getStyleId() != null && decoration == null) {
				decoration = new DecorationVO();
				decoration.setStyleId(detail.getStyleId());
				decoration.setStyleName(detail.getStyleName());
				decoration.setStyleCode(detail.getStyleCode());
				styleMap.put(detail.getStyleId(), decoration);
			}
			// 组装页面配置(一种风格对应该多个页面)
			PageVO page = pageMap.get(detail.getPageId());
			if (detail.getPageId() != null && page == null) {
				if (page == null) {
					page = new PageVO();
					page.setPageId(detail.getPageId());
					page.setPageName(detail.getPageName());
					page.setPageCode(detail.getPageCode());
					pageMap.put(detail.getPageId(), page);
					decoration.getPage().put(page.getPageCode(), page);
				}
			}

			// 组装模块配置(一个页面对应多个模块)
			ModuleVO module = moduleMap.get(detail.getModuleCode());
			if (detail.getModuleId() != null && module == null) {
				module = new ModuleVO();
				module.setModuleId(detail.getModuleId());
				module.setModuleName(detail.getModuleName());
				module.setModuleCode(detail.getModuleCode());
				moduleMap.put(detail.getModuleCode(), module);
				page.getModule().put(detail.getModuleCode(), module);
			}

			// 组装组件分组配置(一个模块对应多个组件分组)
			List<ComponentGroupVO> componentGroupList = tempComponentGroup.get(detail.getComponentgroupCode());
			ComponentGroupVO componentGroup = new ComponentGroupVO();
			if (detail.getComponentgroupId() != null && CollectionUtils.isEmpty(componentGroupList)) {
				componentGroup.setComponentgroupId(detail.getComponentgroupId());
				componentGroup.setComponentgroupName(detail.getComponentgroupName());
				componentGroup.setComponentgroupCode(detail.getComponentgroupCode());

				componentGroupList = new ArrayList<ComponentGroupVO>();
				componentGroupList.add(componentGroup);
				tempComponentGroup.put(detail.getComponentgroupCode(), componentGroupList);
				module.getComponentGroup().put(detail.getComponentgroupCode(), componentGroupList);
			}

			// 组装具体组件配置(一个组件分组拥有多个组件)
			List<ComponentVO> componentList = tempComponent.get(detail.getComponentCode());
			if (detail.getComponentId() != null) {
				ComponentVO component = new ComponentVO();
				component.setComponentId(detail.getComponentId());
				component.setComponentName(detail.getComponentName());
				component.setComponentCode(detail.getComponentCode());
				component.setPropsName(detail.getPropsName());
				component.setContext(detail.getContext());
				component.setImg(detail.getImg());
				component.setUrl(detail.getUrl());
				if (CollectionUtils.isEmpty(componentList)) {
					componentList = new ArrayList<ComponentVO>();
					componentList.add(component);
				} else {
					componentList.add(component);
				}
				tempComponent.put(detail.getComponentCode(), componentList);
				// 如果组件分组已存在，则将组件放到组件分组下
				if (!CollectionUtils.isEmpty(componentGroupList)) {
					for (ComponentGroupVO group : componentGroupList) {
						if (group.getComponentgroupCode() != null
								&& group.getComponentgroupCode().equals(detail.getComponentgroupCode())) {
							group.getComponent().put(detail.getComponentCode(), componentList);
							break;
						}
					}
				} else {
					componentGroup.getComponent().put(detail.getComponentCode(), componentList);
				}
			}
		}
		res.setData(decoration);
		return res;
	}

	@Override
	public CoreResponse<AlipayMarketingTriggerVO> getMarketingTrigger(String telNumber, String userId, String loginId, Integer source) {
		
		CoreResponse<AlipayMarketingTriggerVO> res = new CoreResponse<AlipayMarketingTriggerVO>();
		AlipayMarketingTriggerVO alipayVO = new AlipayMarketingTriggerVO();
		AlipayClient alipayClient = new DefaultAlipayClient(AlipayServiceEnvConstants.ALIPAY_GATEWAY.getValue(),
				sweepOrderAppId, AlipayServiceEnvConstants.PRIVATE_KEY.getValue(), "json",
				AlipayServiceEnvConstants.CHARSET.getValue(), AlipayServiceEnvConstants.ALIPAY_PUBLIC_KEY.getValue(),AlipayServiceEnvConstants.SIGN_TYPE.getValue());

		AlipayMarketingCampaignDrawcampTriggerRequest request = new AlipayMarketingCampaignDrawcampTriggerRequest();
		JSONObject json = new JSONObject();
		//手机号领取红包
		if (StringUtils.isNotEmpty(telNumber)) {
			json.fluentPut("bind_mobile", telNumber);
		//登录账号领取红包
		} else if (StringUtils.isNotEmpty(loginId)) {
			json.fluentPut("login_id", loginId);
		//支付宝用户id领取红包
		} else if (StringUtils.isNotEmpty(userId)) {
			json.fluentPut("user_id", userId);
		}
		//请求来源，目前支持：1微信 2 微博 3虾米 4淘宝 5天猫  
//		if(source!=null){
//			json.fluentPut("camp_source", source);
//		}
//		json.fluentPut("json_ua", "1111111111111111");
//		json.fluentPut("channel_info", "{level1:mapp,level2:hz}");
		//客户端ip
//		json.fluentPut("client_ip", "111.111.111.111");
		//余额宝消费红包活动id
		json.fluentPut("camp_id","75335");
		request.setBizContent(json.toJSONString());
		AlipayMarketingCampaignDrawcampTriggerResponse response;
		try {
			response = alipayClient.execute(request);
			//调余额宝消费红包活动，不中奖再调实体店通用红包活动
			if (response == null || !response.isSuccess()
					|| (!response.getTriggerResult() && (("CAMP_NOT_VALID")
							.equals(JSONObject.parseObject(response.getExtendField()).getString("errorMsgType"))
							|| ("NOT_WIN").equals(
									JSONObject.parseObject(response.getExtendField()).getString("errorMsgType"))))) {
				//实体店通用红包活动id
				json.fluentPut("camp_id", "61406");
				request.setBizContent(json.toJSONString());
				response = alipayClient.execute(request);
				if(response != null && response.isSuccess()){
					BeanUtils.copyProperties(response, alipayVO);
					//2为实体店领取红包
					alipayVO.setTriggerType(2);
				}
			} else if (response != null && response.isSuccess()) {
				BeanUtils.copyProperties(response, alipayVO);
				//1为余额宝消费红包
				alipayVO.setTriggerType(1);
			}
			if (response == null || !response.isSuccess()) {
				BeanUtils.copyProperties(response, alipayVO);
				if(alipayVO.getTriggerType()==null){
					alipayVO.setTriggerType(2);
				}
				//前端需要转成json格式
				if(response.getExtendField()!=null){
					alipayVO.setExtendField(JSON.parseObject(response.getExtendField()));
				}
				res.setData(alipayVO);
				res.setSubMsg("调用支付宝接口失败，领取红包失败");
				return res;
			}
			//前端需要转成json格式
			if(response.getExtendField()!=null){
				alipayVO.setExtendField(JSON.parseObject(response.getExtendField()));
			}
			res.setData(alipayVO);
			res.setSubMsg("领取成功");
			return res;
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
			res.setStatusInfo(StatusInfo.FORBIDDEN);
			res.setSubMsg("调用支付宝红包接口异常，领取红包失败");
			return res;
		}
	}

	@Override
	public Map<String, Integer> getShowPeopleNumber(ShowPeopleNumberVO showPeopleNumber) {

		Map<String, Integer> showMap = new HashMap<String, Integer>();
		// 能否修改人数
		showMap.put("showPeopleNum", 0);
		String startDate = DateUtils.getYesterdayStartTime();
		String endDate = DateUtils.getTodayEndTime();
		String nowDate = DateUtils.getNowTime();
		DiningArea diningArea = null;
		// 获取桌台信息
		if (showPeopleNumber.getTableInfoId() != null) {
			diningArea = shopperInfoServiceApi.getDiningAreaById(showPeopleNumber.getTableInfoId());
		}
		// 获取必选菜信息查询条件
		GoodsExtendParam goodsExtendParam = new GoodsExtendParam();
		goodsExtendParam.setStoreId(showPeopleNumber.getStoreId());
		goodsExtendParam.setShopperId(showPeopleNumber.getShopperId());
		if (diningArea != null) {
			goodsExtendParam.setTableUid(diningArea.getUid());
		}
		goodsExtendParam.setStartDate(startDate);
		goodsExtendParam.setEndDate(endDate);
		goodsExtendParam.setNowDate(nowDate);
		// 查询进行中订单状态
		Waimai waimai = waimaiOrderService.getMyOrderStatus(showPeopleNumber.getStoreId(),
				(diningArea == null ? null : diningArea.getName()), showPeopleNumber.getBuyerId(),null);
		// 当订单为加菜订单时获取必点菜是否跟人数相关
		if (waimai != null && waimai.getPayStatus() != 1) {
			// 获取必选菜商品信息
			List<CategoryGoods> needGoods = shopperGoodsServiceApi.getNeedGoodsInfoList(goodsExtendParam);
			if (!CollectionUtils.isEmpty(needGoods)) {
				for (CategoryGoods goods : needGoods) {
					if (goods.getIsRelatedPerson() != null && goods.getIsRelatedPerson() >= 1) {
						showMap.put("showPeopleNum", 1);
						break;
					}
				}
			}
		}
		return showMap;
	}

	@Override
	public CoreResponse<QrcodeVO> getAnalyzeQrcodePath(Integer storeId, Long thirdUserInfoId, String url, Integer mode) {
		CoreResponse<QrcodeVO> res = new CoreResponse<QrcodeVO>();
		Map<String,Object> map = new HashMap<String,Object>();
		String pathUrl = "";
		List<String> list = new ArrayList<String>();
		list.add("http://openapi.blibao");
		list.add("http://b2b.blibao.com");
		list.add("http://test.blibao.com");
		list.add("http://test.api.blibao.com");
		list.add("https://openapi.blibao.com");
		list.add("https://b2b.blibao.com");
		String urlStr = url.substring(0,url.indexOf(".com")+4);
		//api域名解析
		if (list.contains(urlStr)){
			map = getAnalyzeUrl(url);
			if(map!=null && map.get("guid")!=null){
				String guid = String.valueOf(map.get("guid"));
				//获取二维码绑定信息
				Qrcode qrcode = shopperInfoServiceApi.getQrcodeInfoByGuid(guid);
				if(qrcode!=null && qrcode.getBindShopId()!=null && storeId.equals(qrcode.getBindShopId())){
					//店铺码
					if(new Integer(1).equals(qrcode.getBindType())){
						pathUrl = sweepOrderVueUrl + "mini/miniProgramRedirectPath?storeId=" + storeId
								+ "&thirdUserInfoId=" + thirdUserInfoId + "&source=" + mode + "&orderSource=" + 1;
						//桌台码
					}else if(new Integer(2).equals(qrcode.getBindType()) && qrcode.getBindTableId()!=null){
						pathUrl = sweepOrderVueUrl + "mini/miniProgramRedirectPath?storeId=" + storeId
								+ "&thirdUserInfoId=" + thirdUserInfoId + "&source=" + mode + "&tableInfoId="
								+ qrcode.getBindTableId() + "&orderSource=" + 1;
					}
				}
			}else{
				//b2b域名解析
				if(map!=null && map.get("shopperId")!=null && storeId.equals(map.get("shopperId"))){
					if(map.get("tableInfoId")!=null){
						pathUrl = sweepOrderVueUrl + "mini/miniProgramRedirectPath?storeId=" + storeId
								+ "&thirdUserInfoId=" + thirdUserInfoId + "&source=" + mode + "&tableInfoId="
								+ Integer.valueOf(String.valueOf(map.get("tableInfoId"))) + "&orderSource=" + 1;
					}else{
						pathUrl = sweepOrderVueUrl + "mini/miniProgramRedirectPath?storeId=" + storeId + "&thirdUserInfoId="
								+ thirdUserInfoId + "&source=" + mode + "&orderSource=" + 1;
					}
				}
			}
		}
		QrcodeVO qrcodeVO = new QrcodeVO();
		if(StringUtils.isEmpty(pathUrl)){
			qrcodeVO.setSuccess(false);
			qrcodeVO.setMsg("无法解析该二维码url="+url);
		}else{
			qrcodeVO.setPathUrl(pathUrl);
			qrcodeVO.setMsg("解析成功");
		}
		res.setData(qrcodeVO);
		return res;
	}
	
	public Map<String,Object> getAnalyzeUrl(String url){
		Map<String,Object> map = new HashMap<String, Object>();
		String strUrlParams = "";
		//解析访问地址
		if(url.contains("?")){
			String[] strUrlPatten = url.split("\\?");
			strUrlParams = strUrlPatten[1];
			//解析参数
			String[] params = null;
			if(strUrlParams.contains("&")){
				params = strUrlParams.split("&");			
			}else{
				params = new String[] {strUrlParams};
			}
			//保存参数到参数容器
			for(String p:params){
				if(p.contains("=")) {
					String[] param = p.split("=");
					map.put(param[0], param[1]);
				}
			}
		}
		return map;
	}

	@Override
	public CoreResponse<AppointmentTimeVO> getAppointmentTime(Integer storeId, Integer shopId, String date) {
		CoreResponse<AppointmentTimeVO> res = new CoreResponse<AppointmentTimeVO>();
		   try {
			    if(StringUtils.isEmpty(date)){
			    	date = new SimpleDateFormat("yyyy-MM-dd").format(new Date()).toString();
			    }
			    AppointmentTimeVO appointmentTimeVO = new AppointmentTimeVO();
			    // 获取亚心医院点餐信息
			    List<ReserveBasicInfo> list = shopperInfoServiceApi.getReserveBasicInfo(shopId, storeId);
			    if(CollectionUtils.isEmpty(list)){
			    	res.setStatusInfo(StatusInfo.FORBIDDEN);
					res.setSubMsg("暂时没有查询到配置的预约取餐信息");
					return res;
			    }
			    // add by ywc 2019年10月15日 	获取店铺营业时间和打烊时间，营业时间与打烊时间冲突时，已打烊为准（即不可预约）
			    // 当前时间如果不在营业时间，或者在打烊时间，则不可预约
			    boolean reserveFlag = true;
			    ShopperExtend shopperExtend = shopperInfoServiceApi.getShopperExtend(storeId);
			    if (null != shopperExtend) {
			    	JSONObject businessTimeJson = getStartAndEndStoreTime(shopperExtend.getBusinessTime(), 1);
				    JSONObject closingTimeJson = getStartAndEndStoreTime(shopperExtend.getClosingTime(), 2);
			    	reserveFlag = getReserveFlag(businessTimeJson, closingTimeJson);
			    }
			    for(ReserveBasicInfo reserveBasicInfo : list){
			    	
					// 将map转成实体
				    ReserveBasicInfoVO reserveBasicInfoVO = new ReserveBasicInfoVO();
			    	BeanUtils.copyProperties(reserveBasicInfo, reserveBasicInfoVO);
			    	if (!reserveFlag) {
			    		reserveBasicInfoVO.setReserveStatus(2);
			    	} else {
			    		// 获取reids里面各个时间段预约数
					    Integer num = 0;
					    String key = "";
				    	key = KeyGenerateRulesUtils.getAppointmentTimeKey(String.valueOf(shopId),String.valueOf(storeId), date, reserveBasicInfo.getReserveTime());
				    	num  = redisService.getObj(key) == null?0:Integer.valueOf(redisService.getObj(key).toString());
				    	// 先判断是否在现在的时间和当前最迟下单时间比较 
				    	String latestTimeStr = date + " " + reserveBasicInfo.getReserveLatestTime() + ":00";
				    	Calendar c = Calendar.getInstance();
				    	c.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(latestTimeStr));
				    	Long latestTimeSec = c.getTimeInMillis();
				    	c.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(CalendarUtil.DateToString(new Date())));
				    	Long nowTimeSec = c.getTimeInMillis();
				    	//logger.info("最晚预约时间："+latestTimeStr +"当前时间戳："+nowTimeSec+"最晚预约时间戳："+latestTimeSec);
				    	if(nowTimeSec < latestTimeSec){
				    		// 比较该时间段总的预约数和可预约单量
				    		if (new Integer(-1).equals(reserveBasicInfo.getReceiveCount())) {
				    			reserveBasicInfoVO.setReserveStatus(-1);
				    		} else if(num < reserveBasicInfo.getReceiveCount()){
					    		reserveBasicInfoVO.setReserveStatus(0);
					    	}else{
					    		reserveBasicInfoVO.setReserveStatus(1);
					    	}
				    	}else{
				    		reserveBasicInfoVO.setReserveStatus(2);
				    	}
			    	}
			    	appointmentTimeVO.getReserveBasicInfo().add(reserveBasicInfoVO);
			    }
			    appointmentTimeVO.setCurrentDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()).toString());
			    appointmentTimeVO.setCurrentAfterDate(CalendarUtil.formatDateByString(CalendarUtil.getDateByMethod(CalendarUtil.DateToString(new Date()), "add")));
			    
			    // add by ywc 2019年10月14日 	餐段根据所有预约时间分组获取
			    List<String> reserveStageList = shopperInfoServiceApi.getReserveStageListByStoreId(shopId, storeId);
			    appointmentTimeVO.setReserveStageList(reserveStageList);
			    res.setData(appointmentTimeVO);
			    res.setMsg("获取亚心医院预约时间成功！");
			    res.setStatusInfo(StatusInfo.SUCCESS);
			} catch (Exception e) {
				logger.error("获取亚心医院预约时间异常：" + Utils.log4jDetail(e));
		    	res.setStatusInfo(StatusInfo.BUSINESS);
				res.setSubMsg("获取亚心医院预约时间异常");
				e.printStackTrace();
			}
		   return res;
	    
	}
	  /**
     * 获取店铺营业时间的开始、结束时间
     * @param storeTime		时间段
     * @param type			1：营业时间，2：打烊时间
     * @return
     */
    private static JSONObject getStartAndEndStoreTime(String storeTime, int type) {
    	// 默认全天营业，无打烊时间
    	String startStoreTime = "00:00";
    	String endStoreTime = "00:00";
    	JSONObject newStoreTime = new JSONObject();
    	newStoreTime.put("startStoreTime", startStoreTime);
    	newStoreTime.put("endStoreTime", endStoreTime);
    	if (StringUtils.isEmpty(storeTime) && type == 1) {
    		return newStoreTime;
    	} else if (StringUtils.isEmpty(storeTime) && type == 2) {
    		return null;
    	}
		try{
			startStoreTime = storeTime.split("~")[0];
			endStoreTime = storeTime.split("~")[1];
		}catch(Exception e){
			e.printStackTrace();
			if (type == 1) {
				startStoreTime = "00:00";
				endStoreTime = "00:00";
			} else if (type == 2) {
				return null;
			}
		}
		newStoreTime.put("startStoreTime", startStoreTime);
    	newStoreTime.put("endStoreTime", endStoreTime);
		return newStoreTime;
    }
    
    /**
     * 判断当前时间是否可预约
     * @param businessTimeJson
     * @param closingTimeJson
     * @return
     */
    private static boolean getReserveFlag (JSONObject businessTimeJson, JSONObject closingTimeJson) {
    	boolean reserveFlag = true;
    	String businessStartTime = businessTimeJson.getString("startStoreTime");
    	String businessEndTime = businessTimeJson.getString("endStoreTime");
    	
    	// 先判断是否在营业时间内
    	if (DateUtils.isNowBetweenTimes(businessStartTime, businessEndTime)) {
			reserveFlag = true;
		} else {
			reserveFlag = false;
		}
    	// 有打烊时间且在营业时间内，需要再次判断是否在打烊时间内
    	if (null!=closingTimeJson && reserveFlag) {
    		String closingStartTime = closingTimeJson.getString("startStoreTime");
    		String closingEndTime = closingTimeJson.getString("endStoreTime");
    		if (DateUtils.isNowBetweenTimes(closingStartTime, closingEndTime)) {
    			reserveFlag = false;
    		}
    	}
    	return reserveFlag;
    }

	@Override
	public CoreResponse<String> appointmentVerification(ReserveBasicInfoVO reserveBasicInfoVO,String date) {
		//logger.info("date:"+date);
		CoreResponse<String> result = new CoreResponse<String>();
		 if(StringUtils.isEmpty(date)){
		    	date = new SimpleDateFormat("yyyy-MM-dd").format(new Date()).toString();
		  } 
		// 获取redis中的数据
    	try {
    		// add by ywc 2019年10月15日 	获取店铺营业时间和打烊时间，营业时间与打烊时间冲突时，已打烊为准（即不可预约）
		    // 当前时间如果不在营业时间，或者在打烊时间，则不可预约
		    boolean reserveFlag = true;
		    ShopperExtend shopperExtend = shopperInfoServiceApi.getShopperExtend(reserveBasicInfoVO.getStoreId());
		    if (null != shopperExtend) {
		    	JSONObject businessTimeJson = getStartAndEndStoreTime(shopperExtend.getBusinessTime(), 1);
			    JSONObject closingTimeJson = getStartAndEndStoreTime(shopperExtend.getClosingTime(), 2);
		    	reserveFlag = getReserveFlag(businessTimeJson, closingTimeJson);
		    }
		    if (!reserveFlag) {
		    	result.setStatusInfo(StatusInfo.BUSINESS);
				result.setMsg("该店铺已经打烊了");
	    	} else{
			String key = KeyGenerateRulesUtils.getAppointmentTimeKey(String.valueOf(reserveBasicInfoVO.getShopperId()),String.valueOf(reserveBasicInfoVO.getStoreId()),
					date,reserveBasicInfoVO.getReserveTime());
			Integer num = redisService.getObj(key) == null?0:Integer.valueOf(redisService.getObj(key).toString());
			// 先判断是否在现在的时间和当前最迟下单时间比较 
			String latestTimeStr = date + " " + reserveBasicInfoVO.getReserveLatestTime() + ":00";
			Calendar c = Calendar.getInstance();
			c.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(latestTimeStr));
			Long latestTimeSec = c.getTimeInMillis();
			c.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(CalendarUtil.DateToString(new Date())));
			Long nowTimeSec = c.getTimeInMillis();
			if(nowTimeSec < latestTimeSec){
				// 比较该时间段总的预约数和可预约单量
				if (new Integer(-1).equals(reserveBasicInfoVO.getReceiveCount()) || num < reserveBasicInfoVO.getReceiveCount()) {
					result.setStatusInfo(StatusInfo.SUCCESS);
					result.setMsg("可以点餐");
				} else{
					result.setStatusInfo(StatusInfo.BUSINESS);
					result.setMsg("该时间段已经预约满了");
				}
			}else{
				result.setStatusInfo(StatusInfo.BUSINESS);
				result.setMsg("已经过了最晚预约点餐时间段了");
			}
	    }
		}catch (Exception e) {
			e.printStackTrace();
			result.setStatusInfo(StatusInfo.BUSINESS);
			result.setMsg("预约点餐验证异常");
		}
		return result;
	}

	@Override
	public CoreResponse<EmployeeAuthRecordEntryVO> isExistEmployeeAuthRecord(Integer shopId, Integer storeId,
			String source, String appId, String buyerId, int type) {
		CoreResponse<EmployeeAuthRecordEntryVO> res = new CoreResponse<EmployeeAuthRecordEntryVO>();
		res=employeeService.isExistEmployeeAuthRecord(shopId, storeId, source, appId, buyerId, type);
		return res;
	}

	@Override
	public void saveOrUpdateEmployeeAuthRecord(Integer employeeAuthId, Integer shopId, Integer storeId,
			Integer employeeId, String source, String appId, String buyerId) {
		employeeService.saveOrUpdateEmployeeAuthRecord(employeeAuthId, shopId, storeId, employeeId, source, appId, buyerId);
		
	}

	@Override
	public CoreResponse<FindEmployeeEntryVO> getShopEmployeeIdByMobile(Integer shopId, Integer storeId,
			String phone) {
		CoreResponse<FindEmployeeEntryVO> res = new CoreResponse<FindEmployeeEntryVO>();
		res=employeeService.getShopEmployeeIdByMobile(shopId, storeId, phone);
		return res;
	}

    //是否享受会员价
    @Override
    public boolean isEnjoyMemberPrice(UserBaseDto userBaseDto, ShopperConfigExtend shopperConfigExt){
        if(!Utils.isEmpty(userBaseDto.getMemberId())){
            if(Constants.SetGoodsUserVipPriceMode.VIP_MEMBER.getValue().equals(shopperConfigExt.getSetGoodsUserVipPriceMode())){
                if(PayMotionConstants.Whether.TRUE.getValue().equals(userBaseDto.getIsVip())){
                    return true;
                }else{
                    return false;
                }
            }else {
                return true;
            }
        }else {
            return false;
        }
    }
}
